﻿CREATE PROCEDURE [dbo].[CashRegisterShiftsInsert]
(
	@CashRegisterId int,
	@OpenUserId int,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)  --Добавление записи в таблицу CD.CashRegisterShifts означает открытие кассы
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @datOpenDT datetime, @intNextId int

SET NOCOUNT ON

IF (@CashRegisterId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (@OpenUserId Is Null)
BEGIN
	SELECT @OpenUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()
	IF (@OpenUserId Is Null)
	BEGIN
		SELECT @intErrCode = 2, @strMsg = 'Не найден идентификатор для пользователя ' + suser_sname() + ' !'
		RAISERROR(@strMsg, 11, @intErrCode )
		RETURN @intErrCode
	END
END

IF EXISTS (SELECT Id FROM CD.CashRegisterShifts WHERE CashRegisterId = @CashRegisterId AND CloseDT IS NULL )
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Для кассы с идентификатором ' + cast(@CashRegisterId as varchar(10)) + ' существует незакрытая смена !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SET @datOpenDT = getdate()
EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CD].[CashRegisterShifts] (Id, [CashRegisterId], [OpenUserId], [OpenDT], [Note], [MD], [MW]) 
VALUES ( @intNextId, @CashRegisterId, @OpenUserId, @datOpenDT, @Note, @MD, @MW);
	
SELECT Id, DepartmentId, CashRegisterId, OpenUserId, OpenDT, CloseUserId, CloseDT, Note, MD, MW 
FROM CD.CashRegisterShifts WHERE (Id = @intNextId)

RETURN 0